package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//@Component
public class SecurityService implements UserDetailsService {

    @Reference(version = "1.0")
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询
        //1. 根据用户名 查询 密码
        //2. 得到用户id，根据用户id查询 所有的角色
        //3. 根据角色id  查询对应的所有权限
        //4. 构造权限列表
        //5. 生成 User对象（security） 用户名 密码 权限列表
        User user = userService.findUserByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        Long userId = user.getId();
        String password = user.getPassword();
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Role> roleList = userService.findRoleListByUserId(userId);
        for (Role role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            List<Permission> permissionList = userService.findPermissionByRoleId(role.getId());

            for (Permission permission : permissionList) {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new org.springframework.security.core.userdetails.User(username,password,authorities);
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("admin"));
    }
}
